<!--  -->
<template>
  <div>
    <!-- 搜索框 -->
    <van-search v-model="value" input-align="center" placeholder="商品搜索 发现好物" />
    <!-- 侧边导航 -->
    <van-tree-select height="80vh" :items="items" :main-active-index.sync="active" @click-nav="clickNav">
      <template #content>
        <!-- 背景图 -->
        <van-image :src="bannerImg"/>
          <!-- 宫格 -->
        <van-grid :column-num="3">
          <van-grid-item v-for="(sub, index) in subCategoryList" :key="index" :icon="sub.wap_banner_url" :text="sub.name" :to="'/categoryList/'+sub.id" />       
        </van-grid>
      </template>
    </van-tree-select>
    <tab-btn></tab-btn>
  </div>
</template>

<script>
import tabBtn from '../components/tabBtn'
import axios from 'axios'
import api from '../assets/config/api'
export default {
  data () {
    return {
      value: '',
      data: [],
      active: '',
      categoryList: [],
      subCategoryList: [],
      bannerImg:'',
    }
  },
  methods: {
    // 获取侧边导航索引值用来ajax请求宫格的内容
    clickNav(index) {
      this.active = index
    },
 
  },
  computed: {
    // 侧边导航内容
    items() {
      if (this.data.data) {
        let arr = []
        this.categoryList.forEach((item, index) => {
          item.text = item.name
          arr.push(item)
        })
        return arr
      } else {
        return []
      }
    }
  },
  watch: {
    // 侧边导航索引值改变，做ajax请求
    active: async function() {
      if (this.items.length !== 0) {
        let id = this.items[this.active].id
        // console.log(id)
        let res = await axios.get(api.CatalogCurrent,{params:{id}})
        // console.log(res)
        // 宫格内容
         this.subCategoryList = res.data.data.currentCategory.subCategoryList
        //  背景图
         this.bannerImg = this.items[this.active].banner_url
      }else {
        this.subCategoryList = []
      }
    }
  },
  components: {
    tabBtn
  },
  async created() {
    let res = await axios.get(api.CatalogList)
    // console.log(res.data)
    this.categoryList = res.data.data.categoryList
    this.bannerImg = res.data.data.currentCategory.banner_url
    this.clickNav(0)
    return this.data = res.data
    
  },
}
</script>

<style scoped>

</style>
